package com.momo.mal.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.momo.mal.Login;
import com.momo.mal.database.MalDatabaseAdapter;

public class DialogLogout extends SherlockDialogFragment {
	private Context context;
	
    public DialogLogout newInstance(Context context) {
    	DialogLogout dialog = new DialogLogout();
    	dialog.context = context;
    	
        return dialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		
        builder.setTitle("Warning");
        builder.setMessage("Your data will be automatically deleted, are you sure?");
		builder.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								new RequestLogout(getActivity()).execute();
							}
						})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		return builder.create();
    }
    
    private class RequestLogout extends AsyncTask<Void, Void, Void> {
		private ProgressDialog dialog;
		
		public RequestLogout(Context context) {
			dialog = new ProgressDialog(context);
			dialog.setMessage("Please wait");
			dialog.setCancelable(false);
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			MalDatabaseAdapter dbAdapter = new MalDatabaseAdapter(getActivity());
			
			SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Login.PREFS_NAME,
					getActivity().MODE_PRIVATE);
			SharedPreferences.Editor editor = sharedPreferences.edit();
			editor.clear();
			editor.commit();
			
			dbAdapter.deleteAllAnime();
			dbAdapter.deleteAllManga();
			dbAdapter.deleteHistory();
			return null;
		}
		
		@Override
		protected void onPreExecute() {
			dialog.show();
		}
		
		@Override
		protected void onPostExecute(Void result) {
			context.startActivity(new Intent(context, Login.class));
			dialog.dismiss();
		}
	}
}
